package com.yuanxiao.filter;

import com.yuanxiao.fegin.UserServiceClient;
import com.yuanxiao.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
@Component
public class TokenFilter implements GlobalFilter, Ordered {

   /* @Autowired
    private UserServiceClient userServiceClient;*/
    @Reference
    private UserService userService;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        if (path.contains("/user/register")|| path.contains("/user/isRegistered")|| path.contains("/user/login")|| path.contains("/code/create")) {
            return chain.filter(exchange);
        }
        HttpCookie token = request.getCookies().getFirst("token");
        String email="";
        if(token != null){
            email = userService.getEmail(token.getValue());
        }
        if (StringUtils.isEmpty(email)){
            String date="UNAUTH";
            DataBuffer wrap = response.bufferFactory().wrap(date.getBytes());
            return response.writeWith(Mono.just(wrap));
        }


        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
